<?php
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class BBCodeExt_simpletag_plugin_base extends DokuWiki_Syntax_Plugin {

	public $T= ''; // tag name, used for the wrapper in render stage
	public $textwrap= array('', ''); // symbols used to wrap in text mode
	
    function getType() { return 'formatting'; }
    function getPType() { return 'normal'; }
    function getAllowedTypes() { return array('formatting', 'substition', 'disabled'); }   
    function getSort() { return 140; }
    function makepatterns($bbtag) {
		return [ <<<EOT
\[${bbtag}\](?=.*?\x5B/${bbtag}\x5D)
EOT
, "\[/${bbtag}\]" ] ;
	}
	
	function setHTMLtag ($t= null) {
		$this->T= $t;
	}
	
	function settextwraps ($open, $close) {
		$this->textwrap= [ $open, $close ];
	}

    function handle($match, $state, $pos, Doku_Handler $handler) {
        switch ($state) {
          case DOKU_LEXER_ENTER :
            return array($state, [$this->T, $match]);

          case DOKU_LEXER_UNMATCHED :
            return array($state, [$this->T, $match]);

          case DOKU_LEXER_EXIT :
            return array($state, [$this->T, $match]);
           
           case DOKU_LEXER_SPECIAL :
			return array($state, [$this->T, $match]);

        }
        return array();
    }

	function render($mode, Doku_Renderer $renderer, $data) {
		list ($state, $match) = $data;
		list ($tag, $text) = $match;
		if (in_array($mode, ['xhtml', 's5'], true) ) {
			switch ($state) {
				case DOKU_LEXER_ENTER :  {
					$renderer->doc.= "<$tag>";
					break;
				}  
				case DOKU_LEXER_UNMATCHED : {
					$text= $renderer->_xmlEntities($text); // htmlspecialchars($match);
					$renderer->doc .= $text;
					break;
				}
				case DOKU_LEXER_EXIT: {
					$renderer->doc.= "</${tag}>";
					break;
				}
			} // end switch
			return true;
		} else if (in_array($mode, ['text'], true) ) {
			switch ($state) {
				case DOKU_LEXER_ENTER: {
					$renderer->doc.= $this->textwrap[0];
					break;
				}
				case DOKU_LEXER_UNMATCHED: {
					$text= $renderer->_xmlEntities($text); 
					$renderer->doc .= $text;
					break;
				}
				case DOKU_LEXER_EXIT : {
					$renderer->doc.= $this->textwrap[1];
					break;
				}
			}
			return true;
		}

        return false;
    }
}

?>
